<template>
  <Modal title="编辑" width="660" v-model="editModal" :mask-closable="false">
    <Form
      label-position="top"
      :model="params"
      v-if="loading"
      ref="params"
      :rules="ruleValidate"
    >
      <Row :gutter="12">
        <Col span="8">
          <FormItem label="姓名" prop="user_name">
            <Input v-model="params.user_name" placeholder="请输入"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="年龄" prop="age">
            <InputNumber
              @on-change="changeage(params.age)"
              :min="1"
              :max="150"
              v-model="params.age"
              placeholder="请输入"
            ></InputNumber>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="性别">
            <RadioGroup v-model="params.gender">
              <Radio label="1">男</Radio>
              <Radio label="2">女</Radio>
              <Radio label="0">不详</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col span="8" v-for="(item, index) in params.mobile" :key="index">
          <FormItem
            :label="
              params.mobile.length === 1 ? '手机号' : `手机号${index + 1}`
            "
            :prop="'mobile.' + index + '.mobile'"
            :rules="{
              required: +index === 0 ? false : true,
              message: '请输入正确的联系号码',
              pattern: /^\d{10,12}$/,
              trigger: 'blur',
            }"
          >
            <Row type="flex" :gutter="8" justify="start">
              <Col>
                <Input
                  v-model="item.mobile"
                  placeholder="请输入"
                  @on-keyup="
                    item.mobile = item.mobile.replace(/\s+|[\r\n]/g, '')
                  "
                  @on-blur="telrepeat(item.mobile)"
                  v-width="
                    parseInt(index) === 0
                      ? parseInt(index) === params.mobile.length - 1
                        ? 140
                        : 180
                      : parseInt(index) === params.mobile.length - 1
                      ? 100
                      : 140
                  "
                ></Input>
              </Col>
              <!-- <Col v-if="
                                                +index === params.mobile.length - 1 &&
                                                params.mobile[index].mobile
                                            ">
                                    <Button icon="md-add" @click="addmobile"></Button>
                                    </Col> -->
              <Col v-if="+index === params.mobile.length - 1">
                <Button icon="md-add" @click="addmobile"></Button>
              </Col>
              <Col v-if="+index !== 0">
                <Button
                  ghost
                  type="error"
                  @click="closemobile(index)"
                  icon="md-close"
                ></Button>
              </Col>
              <Col>
                <div style="color:#ff9900;font-size:18px" v-if="patientStatus">
                  ！老患者到诊
                </div>
              </Col>
            </Row>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="城市" required>
            <jgcheckcity
              ref="checkcity"
              v-model="city_id"
              @cityvalue="cityvalue"
              :name="`wechatpatient${params.id}`"
            ></jgcheckcity>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="归属人" prop="belong_member_id">
            <Select
              disabled
              v-if="+params.is_share === 1 && +params.source_type !== 1"
              v-model="params.belong_member_id"
              placeholder="请选择"
            >
              <Option
                v-for="item in member"
                :disabled="+item.status === 0 || +item.is_share === 1"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
            <Select
              :disabled="+is_edit_belong_member === 0"
              v-else
              v-model="params.belong_member_id"
              placeholder="请选择"
            >
              <Option
                v-for="item in member"
                :disabled="+item.status === 0 || +item.is_share === 1"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="12">
          <Row type="flex" :gutter="32">
            <Col span="12">
              <FormItem label="一级病种" prop="patient_diseases_id">
                <Select
                  v-model="params.patient_diseases_id"
                  :disabled="params.is_edit_diseases != 1"
                  clearable
                  placeholder="请选择"
                  @on-change="changediseases(params.patient_diseases_id)"
                >
                  <Option
                    v-for="item in diseases"
                    :disabled="+item.status === 0"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
            </Col>
            <Col
              span="12"
              v-show="params.patient_diseases_id"
              v-if="diseases_child.length > 0"
            >
              <FormItem label="二级病种" prop="patient_diseases_child_id">
                <Select
                  v-model="params.patient_diseases_child_id"
                  clearable
                  placeholder="请选择"
                  :disabled="params.is_edit_diseases != 1"
                >
                  <Option
                    v-for="item in diseases_child"
                    :disabled="+item.status === 0"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</Option
                  >
                </Select>
              </FormItem>
            </Col>
          </Row>
        </Col>
        <Col span="8">
          <FormItem
            label="部位"
            prop="body_parts_ids"
            v-show="+params.patient_diseases_id === 1"
            v-if="+params.patient_diseases_id === 1"
          >
            <TreeSelect
              :max-tag-count="3"
              v-model="params.body_parts_ids"
              :data="contlist"
              filterable
              multiple
            ></TreeSelect>
          </FormItem>
          <FormItem label="部位" v-show="+params.patient_diseases_id !== 1">
            <TreeSelect
              :max-tag-count="3"
              v-model="params.body_parts_ids"
              :data="contlist"
              filterable
              multiple
            ></TreeSelect>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div class="demo-drawer-footer" slot="footer">
      <Button style="margin-right: 8px;" @click="closeDrawer('params')"
        >取消</Button
      >
      <Button
        type="primary"
        :loading="remarksloading"
        :disabled="disabled"
        @click="handleDrawers('params')"
        >保存</Button
      >
    </div>
  </Modal>
</template>
<script>
// import jgcheckcity from '@/components/checkcity';
import { mapActions, mapGetters, mapMutations, mapState } from "vuex";
import { PatientList, WxFriend, RetrunVisit } from "@/api/chat";
import {
  patientindexeditinfo,
  patientindexsearchmobile,
  repeatbaiyou,
  patientupdatewxPc,
  patientindexsearchchilddiseases,
} from "@/api/hqapi";
import dayjs from "dayjs";
export default {
  components: {  },
  data() {
    return {
      editModal: false,
      params: {
        id: 0,
        user_name: "",
        age: null,
        mobile: [],
        patient_diseases_id: "",
        patient_diseases_child_id: "",
        belong_member_id: "",
        body_parts_ids: "",
        city_id: [],
        gender: "",
        birthday: "",
      },
      loading: true,
      disabled: false,
      remarksloading: false,
      city_id: [],
      is_edit_belong_member: "", // 是否有归属人修改权限
      patientStatus: false, // 是否老患者到诊状态
      diseases_child: [],
      contlist: [],
      member: [], // 归属人
      diseases: [],
      ruleValidate: {
        user_name: [
          {
            required: true,
            message: "请填写姓名",
            trigger: "blur",
          },
        ],
        age: [
          {
            required: true,
            message: "请填写年龄",
            type: "number",
            trigger: "blur,change",
          },
        ],
        belong_member_id: [
          {
            required: true,
            message: "请选择归属人",
            trigger: "change",
          },
        ],
        patient_diseases_id: [
          {
            required: true,
            message: "请选择一级病种",
            trigger: "change",
          },
        ],
        patient_diseases_child_id: [
          {
            required: true,
            message: "请选择二级病种",
            trigger: "change",
          },
        ],
        city_id: [
          {
            required: true,
            message: "请选择城市",
            type: "string",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("chatwebsocket/wechat", [
      "wxFriendInfo",
      "realname",
      "patientList",
      "covItem",
      "currentWechat",
      "patientList",
    ]),
  },

  methods: {
    ...mapMutations("chatwebsocket/wechat", [
      "setReturnVisit",
      "setPatientList",
      "setWxFriendInfo",
    ]),
    initial(row) {
      // console.log(row,'111');
      this.params.id = row;
      this.editModal = true;
      this.editinfo(row);
    },
    cityvalue(city) {
      this.city_id = city;
      this.params.city_id = city;
    },
    changeage(age) {
      let year = dayjs().$y - age;
      this.params.birthday = `${year}-01-01`;
    },
    addmobile() {
      if (+this.params.mobile.length < 5) {
        this.params.mobile.push({
          mobile: "",
        });
      } else {
        this.$Message.warning("手机号最多添加5个");
      }
    },
    changediseases(pid) {
      patientindexsearchchilddiseases({
        pid: pid,
        patient_user_id: this.id,
      }).then((res) => {
        this.diseases_child = res.list;
        this.params.patient_diseases_child_id = "";
      });
    },
    closemobile(index) {
      this.params.mobile.splice(index, 1);
    },
    telrepeat(data) {
      let config = {
        id: this.params.id === undefined ? 0 : this.params.id,
        mobile: data,
      };
      patientindexsearchmobile(config).then((res) => {
        if (res.result === 1) {
          this.$Message.warning({
            duration: 2.5,
            content: "该手机号码已存在",
          });
        }
      });
      repeatbaiyou({ mobile: data }).then((res) => {
        this.patientStatus = res;
      });
    },
    editinfo(id) {
      this.loading = false;
      this.params.id = id;
      patientindexeditinfo({ id: id }).then((res) => {
        this.drawer = true;
        this.params.user_name = res.user_name;
        this.params.gender = res.gender;
        this.params.age = res.age || null;
        this.params.birthday = res.birthday;
        this.params.mobile = [];
        this.is_edit_belong_member = res.is_edit_belong_member;
        for (let index in res.mobile) {
          this.params.mobile.push({
            mobile: res.mobile[index],
          });
        }
        if (+this.params.mobile.length === 0) {
          this.params.mobile = [
            {
              mobile: "",
            },
          ];
        }
        this.params.patient_diseases_id = res.patient_diseases_id;
        this.params.patient_diseases_child_id =
          res.patient_diseases_child_id === "0"
            ? ""
            : res.patient_diseases_child_id;
        this.params.belong_member_id = this.bool ? "" : res.belong_member_id;
        this.params.body_parts_ids = res.body_parts_ids;
        this.city_id = [
          res.province_id ? res.province_id : "",
          res.city_id ? res.city_id : "",
          res.area_id ? res.area_id : "",
        ];
        this.params.city_id = [
          res.province_id ? res.province_id : "",
          res.city_id ? res.city_id : "",
          res.area_id ? res.area_id : "",
        ];
        // this.params.channel_id = res.channel_id == 0 ? '' : res.channel_id + '';
        this.contlist = res.condition.body_parts;
        this.diseases = res.condition.diseases;
        this.diseases_child = res.condition.diseases_child;
        // this.member = res.condition.member
        this.member = [];
        if (+this.params.is_share === 1 && +this.params.source_type !== 1) {
          this.member.push({
            value: res.belong_member_id,
            label: res.belong_member_name,
          });
        } else {
          for (let item of res.condition.member) {
            this.member.push(...item.children);
          }
        }
        this.loading = true;
      });
    },
    closeDrawer(name) {
      if (name) {
        this.$refs[name].resetFields();
        this.patientStatus = false;
      }
      this.editModal = false;
    },
    handleDrawers(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.remarksloading = true;
          this.disabled = true;
          let mobiles = [];
          for (let item of this.params.mobile) {
            mobiles.push(item.mobile);
          }
          let config = JSON.parse(JSON.stringify(this.params));
          config.body_parts_ids = config.body_parts_ids.join(",");
          config.mobile = mobiles.join(",");
          config.city_id = config.city_id.join(",");
          patientupdatewxPc(config)
            .then(() => {
              this.$Message.success("编辑成功");
              // 获取患者列表
              this.getPatientList(this.covItem);
              // 获取好友信息
              // this.getWxFriendInfo(this.covItem);
              this.editModal = false;
              this.remarksloading = false;
              this.disabled = false;
            })
            .catch(() => {
              this.remarksloading = false;
              this.disabled = false;
            });
        }
      });
    },
    getPatientList(covItem) {
      // console.log(covItem,'getPatientList');
      PatientList({
        wechatid: covItem.wechatid,
        friendid: covItem.friendid,
        accountid: this.currentWechat.accountid,
      }).then((res) => {
        // console.log(res,'getPatientList');
        this.setPatientList(res.list);
        // 获取微聊回访记录
        // this.getReturnVisit(covItem);
      });
    },
    // getReturnVisit(covItem) {
    //     if (!this.patientList.length) return;
    //     // console.log('this.patientList[0].id', this.patientList);
    //     // console.log('this.patientList[0].id', this.patientList[0].id);
    //     RetrunVisit({
    //         patient_user_id: this.patientList[0].id,
    //         wechatid: covItem.wechatid,
    //         friendid: covItem.wechatid,
    //     }).then(res => {
    //         this.setReturnVisit(res.list);
    //     });
    // },
    // getWxFriendInfo(covItem) {
    //     WxFriend({
    //         wechatid: covItem.wechatid,
    //         friendid: covItem.friendid,
    //     }).then(res => {
    //         this.setWxFriendInfo(res);
    //     });
    // },
  },
};
</script>
